package com.xyzh05.webapp.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.model.Department;
import com.xyzh05.model.Role;
import com.xyzh05.model.User;
import com.xyzh05.service.DictItemManager;
import com.xyzh05.util.DateUtil;

public class DepartmentAction extends BaseAction implements Preparable {
	private static final long serialVersionUID = -1627566614444142694L;
	
    private DictItemManager dictItemManager;
    private List<Role> roleList = new ArrayList<Role>();
    private List<Long> userIds = new ArrayList<Long>();
    private List<Long> deptIds = new ArrayList<Long>();
    private List<Department> deptList = new ArrayList<Department>();
    private Department department;
    private User user;
    private Role role;
    private Long id;
	private Long userId;
	private Long deptId;
    private String deptName;
    private String query;
    private Integer resultCode;
    private Integer actionType;


    public Integer getResultCode() {
		return resultCode;
	}

	public void setResultCode(Integer resultCode) {
		this.resultCode = resultCode;
	}

	public List<Long> getDeptIds() {
		return deptIds;
	}

	public void setDeptIds(List<Long> deptIds) {
		this.deptIds = deptIds;
	}

	public List<Department> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<Department> deptList) {
		this.deptList = deptList;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public List<Long> getUserIds() {
		return userIds;
	}

	public void setUserIds(List<Long> userIds) {
		this.userIds = userIds;
	}

	public Integer getActionType() {
		return actionType;
	}

	public void setActionType(Integer actionType) {
		this.actionType = actionType;
	}

	public DictItemManager getDictItemManager() {
		return dictItemManager;
	}

	public void setDictItemManager(DictItemManager dictItemManager) {
		this.dictItemManager = dictItemManager;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public Long getDeptId() {
		return deptId;
	}

	public void setDeptId(Long deptId) {
		this.deptId = deptId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public Long getId() {
		return id;
	}

	public String getDeptName() {
		return deptName;
	}

	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}

	/**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String departmentId = getRequest().getParameter("department.id");
            if (departmentId != null && !departmentId.equals("")) {
                department = departmentManager.get(new Long(departmentId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
    	deptList = departmentManager.search(query, Department.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String delete() {
        departmentManager.remove(department.getId());
        saveMessage(getText("department.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            department = departmentManager.get(id);
        } else {
            department = new Department();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (department.getId() == null);

        departmentManager.save(department);

        String key = (isNew) ? "department.added" : "department.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
    
    /**
     * 查询团体或企业
     */
    public String searchDept(){
    	deptList = departmentManager.getDepartmentByName(deptName);
    	return SUCCESS;
    }
    
    /**
     * 绑定企业申请
     * @return
     */
    public String bindDept(){
    	if(actionType == 1){
    		Short status = roleManager.existUserBind(userId);
    		if(status == Role.STATUS_RUNING){
    			resultCode = 2;
    		}else if(status == Role.STATUS_END){
    			resultCode = 3;
    		}else{
    	    	try {
    	    		user = userManager.get(userId);
    	    		department = departmentManager.get(deptId);
    	    		
    	    		role = new Role();
    	    		role.setName(Role.ROLE_EMPLOYEE);
    	    		role.setRoleType(dictItemManager.get(Role.DEFAULT_ROLE_EMPLOYEE));
    	    		role.setDepartment(department);
    	    		role.setStatus(Role.STATUS_RUNING);
    	    		role.setUpdateTime(DateUtil.getNow());
    	    		role.setUser(user);
    	    		roleManager.saveOrUpdate(role);
    	    		
    	    		resultCode = 1;
    			} catch (Exception e) {
    				resultCode = 5;
    			}
    		}
    	}else{
        	userIds.add(userId);
        	deptIds.add(deptId);
    		try {
        		user = userManager.get(userId);
        		
        		user.setRoleId(Role.DEFAULT_ROLE_USER);    		
    			role = roleManager.get(Role.DEFAULT_ROLE_USER);
    			user.getRoles().clear();
    			user.addRole(role);
    			
    			userManager.saveOrUpdate(user);			

    			roleList = roleManager.getUserBindList(deptIds, userIds, null, Role.STATUS_END);
    			roleManager.remove(roleList.get(0).getId());
				resultCode = 4;
			} catch (Exception e) {
				resultCode = 5;
			}    		
    	}    	
    	return SUCCESS;
    }
    
    /**
     * 员工分组
     */
    public String groupSet(){
    	searchGroupList();
    	return SUCCESS;
    }
    
    public String searchGroup(){
    	deptIds.add(getCurrentDept().getId());
    	roleList =  roleManager.getUserBindList(deptIds, null, Role.DEFAULT_ROLE_EMPLOYEE.shortValue(), null);
    	return SUCCESS;
    }
    
    public void searchGroupList(){
    	department = getCurrentDept().getDepartment();
    	if(department != null){
    		deptList = departmentManager.getDepartmentById(department.getId());
    	}else{
    		deptList = departmentManager.getDepartmentById(getCurrentDept().getId());
    	}    	
    }
    
    public String saveGroup(){
    	try {
    		deptList = departmentManager.getDepartmentByName(deptName);
    		for(Department dept: deptList){
    			if(dept.getDisplayName().equals(deptName) && (dept.getId().equals(getCurrentDept().getId()) || dept.getDepartment().getId().equals(getCurrentDept().getId()))){
    				resultCode = 2;
    				return SUCCESS;
    			}
    		}
    		department = new Department();
    		department.setDictItemByDeptTypeId(dictItemManager.get(Department.SECTION));
    		department.setDepartment(getCurrentDept());
    		if(userId != null){
    			department.setUser(userManager.get(userId));    			
    		}
    		department.setDisplayName(deptName);
    		departmentManager.saveOrUpdate(department);
			resultCode = 1;
		} catch (Exception e) {
			resultCode = 3;
		}
    	return SUCCESS;
    }
    
    public String searchGroupUser(){
    	searchGroupList();
    	department = departmentManager.get(deptId);
    	if(department.getDepartment() == null){
        	deptIds.add(getCurrentDept().getId());
        	for(Department dept : deptList){
        		deptIds.add(dept.getId());
        	}
    	}else{
    		deptIds.add(deptId);
    	}
    	roleList = roleManager.getUserBindList(deptIds, null, Role.DEFAULT_ROLE_EMPLOYEE.shortValue(), null);
    	return SUCCESS;
    }
    
    public String changeGroup(){
    	userIds.add(userId);
    	try {
    		roleList = roleManager.getUserBindList(null, userIds, Role.DEFAULT_ROLE_EMPLOYEE.shortValue(), null);
    		if(roleList != null && roleList.size() > 0){
    			role = roleList.get(0); 
    			if(role.getDepartment().getId().equals(deptId)){
    				resultCode = 2;
    		    	return SUCCESS;    				
    			}
    		}
    		role.setDepartment(departmentManager.get(deptId));
    		roleManager.saveOrUpdate(role);
			resultCode = 1;
		} catch (Exception e) { 
			resultCode = 3;
		}
    	return SUCCESS;
    }
    
    public String auditDept(){
    	try {
    		department = userManager.get(userId).getUserDepartment();
    		department.setStatus(Short.valueOf("0"));
    		departmentManager.saveOrUpdate(department);
			resultCode = 1;
		} catch (Exception e) { 
			resultCode = 0;
		}
    	return SUCCESS;
    }
}